package com.myproject.thread.interrupt;

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

public class Inerrupt {

    public static Map map = new HashMap<String,Thread>();
    private static Object obj = new Object();

    //sleep interrupt
    @Test
    public void method1() throws InterruptedException {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("start");
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    System.out.println("interrupt");;
                }
                System.out.println("end");
            }
        });
        t1.start();
        Thread.sleep(3000);
        t1.interrupt();
    }

    //join interrupt
    @Test
    public void method2() throws InterruptedException {

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("t1 start");
                int count =1;
                while (count==1){}
                System.out.println("t1 end");
            }
        });
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("t2 start");
                Thread t1 = (Thread) map.get("t1");
                try {
                    t1.join();
                } catch (InterruptedException e) {
                    System.out.println("t1 interrupt");
                }
                System.out.println("t2 end");
            }
        });
        map.put("t1",t1);
        map.put("t2",t2);
        t1.start();
        t2.start();

        Thread.sleep(3000);
        t2.interrupt();
    }


    //wait-notify interrupt
    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (obj){
                    System.out.println("t1 get lock");
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        System.out.println("t1 interrupt");
                    }
                    System.out.println("t1 end");
                }
            }
        });

        t1.start();
        Thread.sleep(2000);
        t1.interrupt();


    }


}
